require("lua-xwrt.addon.string")
local string = string
local io = io
local os = os
local pairs, ipairs = pairs, ipairs
local table = table

local type = type
local print = print
local tostring, tonumber = tostring, tonumber

module("lua-xwrt.util")
function get_env()
	t = {}
  local  myenv = io.popen("env")
  for line in myenv:lines() do
		_, _, key, value = string.find(line, "([A-Z_0-9a-z]+)[%=]+(.*)")
--print(line, key, value)
		t[key] = value
	end
--print("-------------------------------------------------------")
	return t
end

function get_post()
	local post = {}
	local char = string.char(255)
	local lowchar = string.char(0)
	local data = os.getenv("QUERY_STRING")
	local method = os.getenv("REQUEST_METHOD")
	if method == nil then return {} end
	if method == "GET" then char = "=" end
	local key, value
	if (data==nil or data=="") and method=="POST" then
		data = io.stdin:read"*a"
		data = string.gsub(data,"[-]+%x+%s+%w+[-]%w+[:]%s+%w+[-]%w+[;]%s+%w+[=]\"","&")
		data = string.gsub(data,"[-][-][-]+%x+[-][-]","")
		data = string.sub(data,2)
		data = string.gsub(data,"\"%s", char)
	end
	for l in string.gmatch(data,"[^&]+") do
		l = string.gsub(l,"["..char.."]%s+",char)
		_, _, key, value = string.find(l, "(.+)%s*["..char.."]%s*(.*)")
		key = string.trim(key)
		value = string.trim(value)
		if key ~= nil then
			post[key]=value
		end
	end
	return post
end

function show_table(t,idx)
	local idx = idx or 0
	local str = string.rep("  ",idx)
	for k, v in pairs(t) do
		if type(v) == "table" then
			print(k)
			show_table(v,idx+1)
		else
			print(str..tostring(k).." => "..tostring(v))
		end
	end
end

-- Load File
function file_load(filename)
	local data = ""
	local error = ""
	local BUFSIZE = 2^15     -- 32K
	local f = file_exists( filename )
	if f == true then
    f = assert(io.open(filename,"r"))   -- open input file
  else f = false end

	if f then 
    while true do
		  local lines, rest = f:read(BUFSIZE, "*line")
		  if not lines then break end
		  if rest then lines = lines .. rest .. '\n' end
      data = data ..lines
    end
  else
    return "No such file or directory", f
	end
	return data, string.len(data)
end

function file_exists( file )
    local f = io.open( file, "r" )
    if f then
        io.close( f )
        return true
    else
        return false
    end
end

function uptime()
	t = {}
	info = io.popen("uptime")
	for linea in info:lines() do
		linea = string.gsub(linea,".+ up ([0-9 a-z]) ","%1")
		local i,e = string.find(linea,", load average: ")
		t["loadavg"]=string.sub(linea,e)
		t["uptime"]=string.sub(linea,0,i-1)
	end		
	info:close()
	
	return t
end

-- To read a tables sort by Keys
function pairsByKeys (t, f)
      local a = {}
      for n in pairs(t) do table.insert(a, n) end
      table.sort(a, f)
      local i = 0      -- iterator variable
      local iter = function ()   -- iterator function
        i = i + 1
        if a[i] == nil then return nil
        else return a[i], t[a[i]]
        end
      end
      return iter
end
